package com.kyrie.security.jwt;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.kyrie.utils.GlobalConstants;
import com.kyrie.utils.OperationCommUtil;
import com.kyrie.utils.SpringContextBean;
import com.kyrie.vo.UserInfoVO;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/***
 * 描述: JWTUtil工具类
 *
 * @author wuxiang
 * @date 2020-04-07 14:44
 */
public class JWTUtil {

    private static OperationCommUtil operationCommUtil = SpringContextBean.getBean(OperationCommUtil.class);

    /**
     * 生成 jwtToken 签名
     */
    public static String createToken(UserInfoVO user) {
        try {
            long EXPIRE_TIME = Long.valueOf(operationCommUtil.getDictValue(GlobalConstants.TYPE_2097,GlobalConstants.TYPE_2097_JWTTOKEN_EXPIRE_TIME,"900000"));
            String SECRET = operationCommUtil.getDictValue(GlobalConstants.TYPE_2097,GlobalConstants.TYPE_2097_SECRET,"kyrie.com.cm");

            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            // 附带username信息
            return JWT.create()
                    .withClaim(GlobalConstants.JWT_CLAIM, JSON.toJSONString(user))
                    //到期时间
                    .withExpiresAt(date)
                    //创建一个新的JWT，并使用给定的算法进行标记
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * 校验 token 是否正确
     */
    public static boolean verify(String token, String user) {
        try {
            String SECRET = operationCommUtil.getDictValue(GlobalConstants.TYPE_2097,GlobalConstants.TYPE_2097_SECRET,"kyrie.com.cm");
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //在token中附带了username信息
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim(GlobalConstants.JWT_CLAIM, user)
                    .build();
            //验证 token
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息
     */
    public static String getUserInfo(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(GlobalConstants.JWT_CLAIM).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


}
